/*
 * @Author: 左盐
 * @LastEditors: 左盐
 */
const superagent = require('superagent');
const config = require('../config/config.js');

class tools {
  constructor() {

  }

  randomRange(minNum, maxNum) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * minNum + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        break;
      default:
        return 0;
        break;
    }
  }


  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  };

  stateJson(data = [], msg = '', code = 200) {
    return {
      code,
      data,
      msg
    }
  }
  /**
   * 透明代理
   * @param {}} ctx 
   * @returns
   */
  async proxy(ctx) {
    try {
      const reqHeader = ctx.headers;
      // console.log(reqHeader);
      const header = {};
      header['Content-Type'] = reqHeader['content-type'];
      if (reqHeader.authorization) {
        header['Authorization'] = reqHeader.authorization;
      }
      console.log('proxy:', {
        header,
        method: ctx.method.toLowerCase(),
        url: ctx.url,
        postParam: ctx.request.body
      });
      const res = await superagent[ctx.method.toLowerCase()].call(this, config.proxy.url + ctx.url).timeout({
          response: 1000 * 1, // Wait 5 seconds for the server to start sending,
          deadline: 1000 * 1 // but allow 1 minute for the file to finish loading.
        })
        .set(header)
        .send(ctx.request.body);
      if (typeof (res.body) === 'object') {
        return res.body;
      } else {
        throw new Error('返回值不是一个json, 请查看响应头或者check数据');
      }
    } catch (e) {
      return {
        code: 500,
        data: [],
        msg: e.message
      }
    }
  }
};


module.exports = tools;
